#include "common.hlsl"

cbuffer cbPerObjectPS : register(b0)
{
	float specExp : packoffset(c0.x);
	float specIntensity : packoffset(c0.y);
	bool  bUseNormal : packoffset(c0.z);
	float4x4 World : packoffset(c1);
}

Texture2D    DiffuseTexture	: register(t0);
Texture2D	 BumpTexture  : register(t1);

struct PS_GBUFFER_OUT
{
	float4 ColorSpecInt : SV_TARGET0;
	float4 Normal : SV_TARGET1;
	float4 SpecPow : SV_TARGET2;
};

PS_GBUFFER_OUT PackGBuffer(float3 BaseColor, float3 Normal, float SpecIntensity, float SpecPower)
{
	PS_GBUFFER_OUT Out;

	float SpecPowerNorm = max(0.00001, (SpecPower - g_SpecPowerRange.x) / g_SpecPowerRange.y);

	Out.ColorSpecInt = float4(BaseColor.rgb, SpecIntensity);
	Out.Normal = float4(Normal * 0.5 + 0.5, 0.0);
	Out.SpecPow = float4(SpecPowerNorm, 0.0, 0.0, 0.0);
	return Out;
}

PS_GBUFFER_OUT RenderScenePS(VS_OUTPUT In)
{
	float4 DiffuseColor = DiffuseTexture.Sample(LinearSampler, In.UV);
	clip(DiffuseColor.w - 0.01);
	float3 NormalColor;
	if (bUseNormal)
	{
		//calc TBN
		NormalColor = BumpTexture.Sample(LinearSampler, In.UV);
		float3 B = cross(In.Normal, (float3)In.Tangent);// *In.Tangent.w;
		float3x3 TBN = float3x3((float3)In.Tangent, B, In.Normal);
		NormalColor = mul(NormalColor, TBN);
	}
	else
		NormalColor = In.Normal;
	
	DiffuseColor *= DiffuseColor;

	return PackGBuffer(DiffuseColor.xyz, NormalColor, specIntensity, specExp);
}